package cuit.campus.taskRunning.deliver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cuit.campus.taskRunning.commons.response.Result;
import cuit.campus.taskRunning.deliver.entry.Deliver;
import cuit.campus.taskRunning.deliver.mapper.DeliverMapper;
import cuit.campus.taskRunning.deliver.service.DeliverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class DeliverServiceImpl extends ServiceImpl<DeliverMapper, Deliver> implements DeliverService {
    @Autowired
    private DeliverMapper mapper;
    @Override
    public boolean saveDeliver(Deliver deliver) {
        //判断是否满足注册条件，账号密码是否为空，是否已经存在同名账户，手机号是否为空
        if(deliver.getRunnerAccount() == null|| deliver.getRunnerAccount().isEmpty()
        ||deliver.getRunnerPassword() == null|| deliver.getRunnerPassword().isEmpty()
        ||deliver.getPhone()==null|| deliver.getPhone().isEmpty()){
            return false;
        }
        if(hasDuplicateName(deliver.getRunnerAccount())){
            return false;
        }

        int insert = mapper.insert(deliver);
        return insert > 0;
    }

    public boolean hasDuplicateName(String name) {
        QueryWrapper<Deliver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("runner_account", name); // 假设判断"name"字段是否重复
        // 统计符合条件的记录数
        long count = mapper.selectCount(queryWrapper);
        return count > 0; // 数量>0说明存在重名
    }

    public Deliver selectByAccount(String account){
        return mapper.selectOne(new QueryWrapper<Deliver>().eq("runner_account", account));

    }

    @Override
    public Result login(String account, String password) {
        Deliver deliver = selectByAccount(account);
        System.out.println(deliver);
        if(deliver==null){
            return Result.fail("没有账号信息");
        }
        String dbPassword = deliver.getRunnerPassword();
        System.out.println(dbPassword);
        System.out.println();
        if (dbPassword == null || dbPassword.trim().isEmpty()) {
            return Result.fail("数据库密码记录为空");
        }
        if (!BCrypt.checkpw(password, dbPassword)) {
            return Result.fail("<账号密码输入错误>");
        }
        return Result.ok(deliver,"登录成功");
    }
}
